<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-cascades"></i> 章节详情
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div>
        <el-button
          :type="
            bookType == 'update_status_end' || bookType == 'update_status_stop'
              ? 'info'
              : 'primary'
          "
          @click="
            bookType == 'update_status_end' || bookType == 'update_status_stop'
              ? onGrayClick(
                  bookType == 'update_status_end'
                    ? '已完结'
                    : bookType == 'update_status_stop'
                    ? '已停更'
                    : ''
                )
              : visible()
          "
          >新增
          {{
            bookType == "update_status_end"
              ? "（已完结）"
              : bookType == "update_status_stop"
              ? "(已停更)"
              : ""
          }}</el-button
        >
        <el-button
          :type="
            bookType == 'update_status_end' || bookType == 'update_status_stop'
              ? 'info'
              : 'primary'
          "
          @click="
            bookType == 'update_status_end' || bookType == 'update_status_stop'
              ? onGrayClick(
                  bookType == 'update_status_end'
                    ? '已完结'
                    : bookType == 'update_status_stop'
                    ? '已停更'
                    : ''
                )
              : visibleAll()
          "
          >批量新增
          {{
            bookType == "update_status_end"
              ? "（已完结）"
              : bookType == "update_status_stop"
              ? "(已停更)"
              : ""
          }}</el-button
        >
      </div>
      <el-table
        class="tableView"
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        element-loading-text="加载中"
        element-loading-spinner="el-icon-loading"
        :fit="true"
        border
        ref="multipleTable"
        header-cell-class-name="table-header"
      >
        <el-table-column
          prop="id"
          label="序号"
          align="center"
          width="100"
          fixed="left"
        ></el-table-column>
        <!-- <el-table-column prop="chapterTitle" label="价格（听币）" width="180"></el-table-column> -->
        <el-table-column
          prop="chapterNo"
          label="章节编号"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="chapterTitle"
          label="章节名称"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="publishDate"
          label="发布时间"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="categoryName"
          label="是否是免费章节"
          align="center"
        >
          <template slot-scope="scope">{{
            scope.row.isFree == 1 ? "是" : "否"
          }}</template>
        </el-table-column>
        <el-table-column prop="speaker" label="是否启用" align="center">
          <template slot-scope="scope">{{
            scope.row.isEnable == 1 ? "是" : "否"
          }}</template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :current-page="query.pageIndex"
          :page-size="query.pageSize"
          :total="pageTotal"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>

    <!-- 编辑弹出框 -->
    <el-dialog title="新增" :visible.sync="editVisible" width="30%">
      <el-form
        ref="form"
        :model="form"
        label-width="70px"
        style="min-width: 300px"
      >
        <el-form-item label="章节名称">
          <el-input style="width: 300px" v-model="form.chapterTitle"></el-input>
        </el-form-item>
        <el-form-item label="章节编号">
          <el-input style="width: 300px" v-model="form.chapterNo"></el-input>
        </el-form-item>
        <!-- 
        <el-form-item label="章节价格">
          <el-input style="width: 300px" v-model="form.price"></el-input>
        </el-form-item> -->

        <el-form-item label="是否免费">
          <el-switch
            v-model="form.free"
            active-color="#13ce66"
            inactive-color="#ff4949"
          ></el-switch>
        </el-form-item>

        <el-form-item label="是否支持下载">
          <el-switch
            v-model="form.download"
            active-color="#13ce66"
            inactive-color="#ff4949"
          ></el-switch>
        </el-form-item>
        <el-form-item label="章节音频">
          <input
            type="file"
            id="fileExport"
            @change="handleFileChange"
            ref="inputer"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEdit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 多选弹出框 -->
    <el-dialog title="新增" :visible.sync="visibleAllModel" width="30%">
      <el-table
        class="tableView"
        :data="upLoadList"
        style="width: 100%"
        :fit="true"
        border
        ref="multipleTable"
        header-cell-class-name="table-header"
        v-if="upLoadList.length > 0"
        type="index"
      >
        <el-table-column
          prop="chapterNo"
          label="章节编号"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="chapterTitle"
          label="章节名称"
          width="180"
        ></el-table-column>

        <el-table-column
          prop="categoryName"
          label="是否是免费章节"
          align="center"
        >
          <template slot-scope="scope">{{
            scope.row.isFree == 1 ? "是" : "否"
          }}</template>
        </el-table-column>
        <el-table-column prop="speaker" label="是否支持下载" align="center">
          <template slot-scope="scope">{{
            scope.row.isDownload == 1 ? "是" : "否"
          }}</template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100" fixed="right">
          <template slot-scope="scope">
            <el-button @click="onDeleteList(scope.row, scope.$index)"
              >删 除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="upLoadFiles">
        <el-button type="primary" class="but">上传文件</el-button>
        <div class="tag">*文件命名格式 例：第520章 山村老尸对降临.mp3</div>
        <div class="tag">*文件命名格式 例：520、山村老尸对降临.mp3</div>
        <input
          :value="binds"
          type="file"
          id="fileExport"
          @change="handleFileChangeAll"
          ref="inputers"
          multiple="multiple"
        />
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="visibleAllModel = false">取 消</el-button>
        <el-button type="primary" @click="saveEditAll">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { fetchData } from "../../api/index";
import Qs from "qs";

export default {
  // name: 'basetable',
  data() {
    return {
      query: {
        pageIndex: 1,
        pageSize: 10,
      },
      loading: true,
      tableData: [],
      editVisible: false,
      visibleAllModel: false,
      pageTotal: 0,
      form: {
        chapterTitle: "",
        publishDate: "",
        isEnable: 1,
        bookId: this.$route.query.bookId,
        chapterNo: "",
        price: 0,
        isFree: 1,
        free: true,
        isDownload: 1,
        download: true,
        anchorId: localStorage.getItem("anchorId"),
        audioObjectName: "",
      },
      formData: "",
      upLoadList: [],
      binds: "",
      flag: 1,
      bookType: "",
    };
  },
  created() {
    this.member_id = this.$route.query.member_id;
    this.bookType = this.$route.query.type;
    console.log("✅-----", this.bookType);
    console.log("asdasd", this.member_id);
    this.getData();
  },
  methods: {
    handleFileChange(e) {
      this.$message("上传中");
      this.flag = 2;
      let inputDOM = this.$refs.inputer;
      console.log(inputDOM.files);
      this.file = inputDOM.files[0]; // 通过DOM取文件数据
      this.formData = new FormData(); //new一个formData事件
      this.formData.append("file", this.file); //将file属性添加到formData里 //此时formData就是我们要向后台传的参数了
      this.$request
        .setUpDataAudio(this.formData)
        .then((res) => {
          console.log("frils", res);
          this.form.audioObjectName = res.data.content.audioObjectName;
          this.flag = 3;
          this.$message({
            message: "恭喜你，上传成功！",
            type: "success",
          });
        })
        .catch((err) => {
          console.log(err);
        });
    },
    onGrayClick(type) {
      this.$message(type);
    },
    handleFileChangeAll(e) {
      this.$message("上传中");
      let inputDOM = this.$refs.inputers,
        upLoadList = this.upLoadList;
      for (let i in inputDOM.files) {
        if (!isNaN(i)) {
          console.log("✅---", inputDOM.files[i].name);
          let listInfo = {
            isFree: 0,
            free: false,
            isDownload: 1,
            download: true,
            isEnable: 1,
            price: 0,
            anchorId: localStorage.getItem("anchorId"),
            bookId: this.$route.query.bookId,
          };
          var splitType = inputDOM.files[i].name.split(""),
            spiltValue = "",
            spiltLast = "",
            type = false;
          for (let t in splitType) {
            console.log(splitType[t]);
            if (splitType[t] == " ") {
              type = true;
            }
          }
          if (type) {
            spiltValue = inputDOM.files[i].name.split(" ")[0];
            spiltLast = inputDOM.files[i].name.split(" ")[1];
          } else {
            spiltLast = inputDOM.files[i].name.split("、")[1];
            spiltValue = inputDOM.files[i].name.split("、")[0];
          }
          console.log(
            "this.getFileid(spiltValue)--------",
            typeof this.getFileid(spiltValue)
          );
          listInfo.chapterNo =
            typeof this.getFileid(spiltValue) === "number"
              ? this.getFileid(spiltValue)
              : this.getFileName(spiltLast);
          listInfo.chapterTitle =
            typeof this.getFileid(spiltValue) === "number"
              ? this.getFileName(spiltLast) : this.getFileid(spiltValue) ;
          this.file = inputDOM.files[i]; // 通过DOM取文件数据
          this.formData = new FormData(); //new一个formData事件
          this.formData.append("file", this.file); //将file属性添加到formData里 //此时formData就是我们要向后台传的参数了
          this.$request
            .setUpDataAudio(this.formData)
            .then((res) => {
              console.log("frils", res);
              listInfo.audioObjectName = res.data.content.audioObjectName;
              console.log("56789", upLoadList);
              upLoadList.push(listInfo);
              this.upLoadList = upLoadList;

              this.$message({
                message: "恭喜你，上传成功！",
                type: "success",
              });
              this.binds = "";
            })
            .catch((err) => {
              console.log(err);
            });
        }
      }
    },
    //获取章节
    getFileid(fileId) {
      console.log("321321", fileId);
      fileId = fileId.split("");
      let info = [];
      for (let i in fileId) {
          if (!isNaN(fileId[i])) {
            info.push(fileId[i]);
          } else {
            console.log("❌❌❌❌");
          }
      }
      console.log(fileId, info.length ? "1" : "2");
      if (!info.length) {
        return this.getFileName(fileId.join(""));
      } else {
        console.log("❌❌");
        info = info.join("");
        return info.length ? Number(info) : info;
      }
    },
    //获取名称
    getFileName(fileName) {
      console.log("321321", fileName);

      fileName = fileName.split(".")[0];
      return fileName;
    },
    visible(e) {
      this.editVisible = true;
    },
    visibleAll() {
      this.visibleAllModel = true;
    },
    getData(e, v) {
      let bookId = this.$route.query.bookId;
      this.$request
        .getChapterByBookId({
          anchorId: 3,
          id: bookId,
          pageNum: this.query.pageIndex,
          pageSize: this.query.pageSize,
        })
        .then((res) => {
          let list = res.data.content.content;
          for (let i in list) {
            console.log(this.timestampToTime(list[i].publishDate));
            list[i].publishDate = this.timestampToTime(list[i].publishDate);
          }
          this.tableData = list;
          this.pageTotal = res.data.content.totalElements;
          this.loading = false;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    timestampToTime(cjsj) {
      var date = new Date(cjsj); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var Y = date.getFullYear() + "-";
      var M =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      var D = date.getDate() + " ";
      var h = date.getHours() + ":";
      var m = date.getMinutes() + ":";
      var s = date.getSeconds();
      return Y + M + D + h + m + s;
    },
    onDeleteList(event, index) {
      console.log(event, index);
      let list = this.upLoadList;
      list.splice(index, 1);
      this.upLoadList = list;
    },
    // 保存编辑
    saveEdit() {
      this.form.isFree = this.form.free ? 1 : 0;
      this.form.isDownload = this.form.download ? 1 : 0;
      this.form.publishDate = Date.now();
      let info = this.form;
      if (this.flag == 1) {
        this.$message.warning("请上传文件");
        return false;
      }
      if (this.flag == 2) {
        this.$message.warning("文件上传中，请上传成功后提交！");
        return false;
      }
      if (!info.chapterTitle || !info.chapterNo || !info.audioObjectName) {
        this.$message.warning("请填写完整信息");
        return false;
      }
      this.$request
        .insteraddChapter(this.form)
        .then((res) => {
          console.log(res);
          if (res.data.statusCode != 200) {
            this.$message.warning(res.data.content);
            return false;
          }
          this.getData();
          this.$message.success("新增章节成功");

          this.editVisible = false;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    onSendFileAll() {
      let list = this.upLoadList;
      for (let i in list) {
        list[i].status = false;
      }
      this.upLoadList = list;
    },
    saveEditAll() {
      let list = this.upLoadList;
      for (let i in list) {
        list[i].isFree = list[i].free ? 1 : 0;
        list[i].isDownload = list[i].download ? 1 : 0;
        list[i].publishDate = Date.now();
        let info = list[i];
        console.log(info, list);
        this.$request
          .insteraddChapter(info)
          .then((res) => {
            console.log(res);
            if (res.data.statusCode != 200) {
              this.$message.warning(res.data.content);
              return false;
            }
            this.getData();
            this.$message.success("新增章节成功");
            this.upLoadList = [];
            this.visibleAllModel = false;
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
    // 分页导航
    handlePageChange(val) {
      this.query.pageIndex = val;
      this.getData();
    },
  },
};
</script>

<style>
.handle-box {
  margin-bottom: 20px;
}

.el-form-item__label {
  width: 200px !important;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.el-dialog {
  width: 65%;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}

.el-dialog {
  min-width: 600px !important;
}
.upLoadFiles {
  position: relative;
}
.upLoadFiles .but {
  margin-top: 20px;
}
.upLoadFiles input {
  position: absolute;
  z-index: 2;
  left: 0;
  top: 0;
  width: 200px;
  height: 90px;
  opacity: 0;
}
.upLoadFiles .tag {
  font-weight: 800;
  color: #ff0000;
}
</style>
